package com.whfc.wxmp.config;

import com.whfc.fuum.entity.WxUser;
import com.whfc.wxmp.annotation.CurrentWxUser;
import com.whfc.wxmp.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class CurrentWxUserArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentWxUser.class)
                && WxUser.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, org.springframework.web.bind.support.WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            Claims claims = JwtUtil.parseToken(token);
            WxUser wxUser = new WxUser();
            Object id = claims.get("id");
            if (id instanceof Integer) {
                wxUser.setId((Integer) id);
            } else if (id != null) {
                wxUser.setId(Integer.parseInt(id.toString()));
            }
            wxUser.setPhone((String) claims.get("phone"));
            wxUser.setName((String) claims.get("name"));
            wxUser.setOpenId((String) claims.get("openId"));
            Object appType = claims.get("appType");
            if (appType instanceof Integer) {
                wxUser.setAppType((Integer) appType);
            } else if (appType != null) {
                wxUser.setAppType(Integer.parseInt(appType.toString()));
            }
            return wxUser;
        }
        return null;
    }
}